package com.hzf.wxplatform.web.controller.manager.owner;

import com.hzf.api.rpc.api.ApiService;
import com.hzf.common.base.BaseController;
import com.hzf.common.util.Arith;
import com.hzf.common.util.ByteUtils;
import com.hzf.common.util.RedisUtil;
import com.hzf.common.util.StringUtil;
import com.hzf.designer.dao.model.*;
import com.hzf.material.dao.model.MaterialGoods;
import com.hzf.material.dao.model.MaterialGoodsExample;
import com.hzf.material.dao.model.MaterialShop;
import com.hzf.material.dao.model.MaterialShopExample;
import com.hzf.money.dao.model.MoneyCashFlow;
import com.hzf.money.dao.model.MoneyUser;
import com.hzf.money.dao.model.MoneyUserExample;
import com.hzf.order.dao.model.*;
import com.hzf.ucenter.dao.model.UcenterUser;
import com.hzf.ucenter.dao.model.UcenterUserCity;
import com.hzf.ucenter.dao.model.UcenterUserExample;
import com.hzf.wxplatform.common.WxplatformResult;
import com.hzf.wxplatform.common.WxplatformResultConstant;
import com.hzf.wxplatform.common.utils.UcenterUserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * describe: TODO
 * creat_user: 白开水
 * creat_time: 2017/12/14   5:44
 **/
@Controller
@RequestMapping("/ownerOrder")
public class   OwnerOrderController extends BaseController {
    @Autowired
    ApiService apiService;
    @RequestMapping(value="/index")
    public String index(Model model, HttpServletRequest request){
        return  thymeleaf("/YZ/YZ_DD_Ticket");
    }
    @RequestMapping(value="/materialOrder")
    public String materialOrder(Model model, HttpServletRequest request){
        byte[] user = UcenterUserUtils.getUser(request.getSession());
        UcenterUser ucenterUser = (UcenterUser) ByteUtils.ByteToObject(user);
        if(null==ucenterUser){
            return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx7146b48eb53f7a2f&redirect_uri=http://hzf.nat100.top/wxOauth/getOpenid&response_type=code&scope=snsapi_userinfo&state=2#wechat_redirect";
        }else{
            OrderUserExample orderUserExample = new OrderUserExample();
            orderUserExample.createCriteria().andUserIdEqualTo(ucenterUser.getId()).andOrderStateEqualTo(0);
            List<OrderUser> orderUsers = apiService.selectOrderList(orderUserExample);
            for(OrderUser orderUser : orderUsers){
                orderUser.setCreatedataTime(StringUtil.dateToString(orderUser.getCreateTime()));
                orderUser.setOrderUserInfoList(apiService.selectByUserByOrderUser(orderUser.getId()));
            }
            model.addAttribute("orderUsers",orderUsers);
        }
        return  thymeleaf("/YZ/YZ_DD_CLiaoTicket");
    }
    @RequestMapping(value="/dneedsDemandOrder")
    public String dneedsDemandOrder(Model model,HttpServletRequest request){
        byte[] a = UcenterUserUtils.getUser(request.getSession());
        if (null == a) {
            model.addAttribute("data", "您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return thymeleaf("/404");
        }
        UcenterUser ucenterUser = (UcenterUser) ByteUtils.ByteToObject(a);
        if (null == ucenterUser) {
            model.addAttribute("data", "您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return thymeleaf("/404");
        }
        DneedsDemandExample dneedsDemandExample = new DneedsDemandExample();
        dneedsDemandExample.createCriteria().andUserIdEqualTo(ucenterUser.getId());
        List<DneedsDemand> list = apiService.selectDneedsDemand(dneedsDemandExample);
        if(null!=list&&0!=list.size()){
            for(DneedsDemand dneedsDemand:list){
                if(dneedsDemand.getDemandType()>0){
                    DneedsBidExample example = new DneedsBidExample();
                    example.createCriteria().andDemandIdEqualTo(dneedsDemand.getId()).andStateGreaterThanOrEqualTo(1);
                    DneedsBid dneedsBid = apiService.getDneedsBid(example);
                    dneedsDemand.setDneedsBid(dneedsBid)       ;
                }
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

                String str=sdf.format(dneedsDemand.getCreateDate());
                dneedsDemand.setCreateTime(str);
            }
        }
        model.addAttribute("data",list);
        return  thymeleaf("/YZ/YZ_DD_Ticketxiang");
    }
    @RequestMapping(value = "/qrsh",method = RequestMethod.POST)
    @ResponseBody
    public Object qrsh(Model model,HttpServletRequest httpServletRequest,Integer id){
        UcenterUser ucenterUser = new UcenterUser();
        ucenterUser = (UcenterUser) ByteUtils.ByteToObject(UcenterUserUtils.getUser(httpServletRequest.getSession()));
        if(null==ucenterUser){
            model.addAttribute("data","您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return  thymeleaf("/404");
        }
        OrderUserInfoExample orderUserInfoExample = new OrderUserInfoExample();
        orderUserInfoExample.createCriteria().andUserIdEqualTo(ucenterUser.getId()).andOrderUserInfoIdEqualTo(id);
        List<OrderUserInfo> orderUserInfos= apiService.selectOrderInfoList(orderUserInfoExample);
        if(0!=orderUserInfos.size()||null!=orderUserInfos){

            OrderUserInfo orderUserInfo = orderUserInfos.get(0);
            orderUserInfo.setPayState(3);
            apiService.updateOrderInfo(orderUserInfo);
            MaterialGoodsExample materialgoodsExample = new MaterialGoodsExample();
            materialgoodsExample.createCriteria().andGoodsIdEqualTo(orderUserInfo.getGoodsId());
            MaterialGoods materialGoods = apiService.selectByGoods(materialgoodsExample);
            materialGoods.setSales(materialGoods.getSales()+1);
            apiService.updateGoods(materialGoods);
            MaterialShopExample materialShopExample = new MaterialShopExample();
            materialShopExample.createCriteria().andShopIdEqualTo(orderUserInfo.getShopId());
            MaterialShop materialShop = apiService.selectByShop(materialShopExample);
            MoneyCashFlow moneyCashFlow = new MoneyCashFlow();
            moneyCashFlow.setShopId(orderUserInfo.getShopId());
            moneyCashFlow.setOrderUserInfoId(orderUserInfo.getOrderUserInfoId());
            moneyCashFlow.setOwnerId(ucenterUser.getId());
            moneyCashFlow.setMaterialId(materialShop.getUserId());
            moneyCashFlow.setCreateTime(System.currentTimeMillis());
            moneyCashFlow.setCashState(0);
            apiService.instalkOrderCash(moneyCashFlow);
            MoneyUserExample moneyUserExample = new MoneyUserExample();
            moneyUserExample.createCriteria().andUserIdEqualTo(ucenterUser.getId());
            MoneyUser moneyUser = new MoneyUser();
            moneyUser=apiService.getMoneyUserFlow(moneyUserExample);

            if(null==moneyUser){
                System.out.println(1);
                MoneyUser moneyUser1 = new MoneyUser();
                moneyUser1.setMoney(orderUserInfo.getPrice());
                moneyUser1.setUserId(materialShop.getUserId());
                moneyUser1.setShopId(materialShop.getShopId());
                apiService.instalkMoneyUserCash(moneyUser1);
            }else{

                moneyUser.setMoney(Arith.add(moneyUser.getMoney(), orderUserInfo.getPrice()));
                apiService.updateMoneyUserCash(moneyUser);
            }
        }else{
            model.addAttribute("data","您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return  thymeleaf("/404");
        }
        return new WxplatformResult(WxplatformResultConstant.SUCCESS, "已收货");


    }
    @RequestMapping(value="/demandInfo",method = RequestMethod.GET)
    private String demandInfo(Integer id,int type,Model model,HttpServletRequest request){
        DecimalFormat df = new DecimalFormat("######0.00");

        UcenterUser ucenterUser = new UcenterUser();
        byte []a = UcenterUserUtils.getUser(request.getSession());
        if(null==a){
            model.addAttribute("data","您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return  thymeleaf("/404");
        }
        ucenterUser = (UcenterUser) ByteUtils.ByteToObject(a);
        if(null==ucenterUser){
            model.addAttribute("data","您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return  thymeleaf("/404");
        }
        String dqaddress = RedisUtil.get("dangqianweizhi"+ucenterUser.getId());
        net.sf.json.JSONObject jsonobject = net.sf.json.JSONObject.fromObject(dqaddress);
        UcenterUserCity usercity= (UcenterUserCity) net.sf.json.JSONObject.toBean(jsonobject,UcenterUserCity.class);

        DneedsDemandExample dneedsDemandExample = new DneedsDemandExample();
        dneedsDemandExample.createCriteria().andUserIdEqualTo(ucenterUser.getId()).andIdEqualTo(id);
        DneedsDemand dneedsDemand = apiService.getDneedsDemand(dneedsDemandExample);

        if(null!=dneedsDemand&&null!=dneedsDemand.getCreateDate()){
            double lat=dneedsDemand.getLat();
            double lng=dneedsDemand.getLng();
            DneedsBidExample example = new DneedsBidExample();
            example.createCriteria().andDemandIdEqualTo(id);
            if(type==0){
                List<DneedsBid> dneedsBids = apiService.selectDneedsBid(example);
                if(null!=dneedsBids&&0!=dneedsBids.size()){
                    for(DneedsBid dneedsBid:dneedsBids){
                        DneedsDesignerExample dneedsDesignerExample = new DneedsDesignerExample();
                        dneedsDesignerExample.createCriteria().andUserIdEqualTo(dneedsBid.getUserId());
                        DneedsDesigner dneedsDesigner = apiService.getDesigner(dneedsDesignerExample);

                        com.github.wenhao.geohash.GeoHash geoHash = com.github.wenhao.geohash.GeoHash.fromLong(dneedsDesigner.getGeoCode());
                        double distance = geoHash.distance(lat, lng);

                        double distanceKm = distance / 1000;
                        dneedsDesigner.setDistanceKm(Double.valueOf(df.format(distanceKm)));
                        DneedsDesignerCaseExample dneedsDesignerCaseExample = new DneedsDesignerCaseExample();
                        dneedsDesignerCaseExample.createCriteria().andUserIdEqualTo(dneedsDesigner.getUserId());
                        List<DneedsDesignerCase> list =apiService.selectDneedsDesignerCase(dneedsDesignerCaseExample);
                        if(null!=list&&0!=list.size()){
                            dneedsDesigner.setAnliCount(list.size());
                        }else{
                            dneedsDesigner.setAnliCount(0);

                        }
                        UcenterUserExample ucenterUserExample = new UcenterUserExample();
                        ucenterUserExample.createCriteria().andIdEqualTo(dneedsDesigner.getUserId());
                        UcenterUser designerUser =apiService.getUser(ucenterUserExample);
                        dneedsDesigner.setPhone(designerUser.getPhone());
                        dneedsDesigner.setUserName(designerUser.getUserName());
                        dneedsBid.setDneedsDesigner(dneedsDesigner);

                    }

                }
                model.addAttribute("dneedsBids",dneedsBids);
            }else{
                DneedsBid dneedsBid = apiService.getDneedsBid(example);
                if(null!=dneedsBid){

                        DneedsDesignerExample dneedsDesignerExample = new DneedsDesignerExample();
                        dneedsDesignerExample.createCriteria().andUserIdEqualTo(dneedsBid.getUserId());
                        DneedsDesigner dneedsDesigner = apiService.getDesigner(dneedsDesignerExample);

                        com.github.wenhao.geohash.GeoHash geoHash = com.github.wenhao.geohash.GeoHash.fromLong(dneedsDesigner.getGeoCode());
                        double distance = geoHash.distance(lat, lng);

                        double distanceKm = distance / 1000;
                        dneedsDesigner.setDistanceKm(Double.valueOf(df.format(distanceKm)));
                        DneedsDesignerCaseExample dneedsDesignerCaseExample = new DneedsDesignerCaseExample();
                        dneedsDesignerCaseExample.createCriteria().andUserIdEqualTo(dneedsDesigner.getUserId());
                        List<DneedsDesignerCase> list =apiService.selectDneedsDesignerCase(dneedsDesignerCaseExample);
                        if(null!=list&&0!=list.size()){
                            dneedsDesigner.setAnliCount(list.size());
                        }else{
                            dneedsDesigner.setAnliCount(0);

                        }
                        UcenterUserExample ucenterUserExample = new UcenterUserExample();
                        ucenterUserExample.createCriteria().andIdEqualTo(dneedsDesigner.getUserId());
                        UcenterUser designerUser =apiService.getUser(ucenterUserExample);
                        dneedsDesigner.setPhone(designerUser.getPhone());
                        dneedsDesigner.setUserName(ucenterUser.getUserName());
                        dneedsBid.setDneedsDesigner(dneedsDesigner);



                }
                model.addAttribute("dneedsBid",dneedsBid);
            }


        }
        model.addAttribute("type",type);

        model.addAttribute("data",dneedsDemand);
        return  thymeleaf("/YZ/YZ_DD_KHSJTicket");
    }
    @RequestMapping(value="/sjsQrsh",method = RequestMethod.POST)
    @ResponseBody
    private Object sjsQrsh(HttpServletRequest request,int id, Model model){
        System.out.println("querenshouhuo");
        UcenterUser ucenterUser = new UcenterUser();
        byte []a = UcenterUserUtils.getUser(request.getSession());
        if(null==a){
            model.addAttribute("data","您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return  thymeleaf("/404");
        }
        ucenterUser = (UcenterUser) ByteUtils.ByteToObject(a);
        if(null==ucenterUser){
            model.addAttribute("data","您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return  thymeleaf("/404");
        }
        DneedsDemandExample dneedsDemandExample = new DneedsDemandExample();
        dneedsDemandExample.createCriteria().andIdEqualTo(id).andUserIdEqualTo(ucenterUser.getId());
        DneedsDemand dneedsDemand =apiService.getDneedsDemand(dneedsDemandExample);
        if(null!=dneedsDemand){
            System.out.println(dneedsDemand.getAddress());

            OrderUserDemandExample orderUserDemandExample = new OrderUserDemandExample();
            orderUserDemandExample.createCriteria().andDemandIdEqualTo(dneedsDemand.getId()).andPayStateEqualTo(1);
            OrderUserDemand orderUserDemand = apiService.getOrderUserDemand(orderUserDemandExample);
            if(null!=orderUserDemand){
                System.out.println(orderUserDemand.getOrderUserId());
                orderUserDemand.setReceivingState(1);
                orderUserDemand.setReceivingTime(System.currentTimeMillis());
                apiService.updateOrderUserDemand(orderUserDemand);
                dneedsDemand.setDemandType(7);
                apiService.updateDneedsDemand(dneedsDemand);
                MoneyCashFlow moneyCashFlow = new MoneyCashFlow();
                moneyCashFlow.setShopId(orderUserDemand.getUserId());
                moneyCashFlow.setOrderUserInfoId(orderUserDemand.getOrderUserId());
                moneyCashFlow.setOwnerId(dneedsDemand.getUserId());
                moneyCashFlow.setMaterialId(orderUserDemand.getUserId());
                moneyCashFlow.setCreateTime(System.currentTimeMillis());
                moneyCashFlow.setCashState(0);
                apiService.instalkOrderCash(moneyCashFlow);
                MoneyUserExample moneyUserExample = new MoneyUserExample();
                moneyUserExample.createCriteria().andUserIdEqualTo(ucenterUser.getId());
                MoneyUser moneyUser = new MoneyUser();
                moneyUser=apiService.getMoneyUserFlow(moneyUserExample);

                if(null==moneyUser){
                    MoneyUser moneyUser1 = new MoneyUser();
                    moneyUser1.setMoney(orderUserDemand.getPrice());
                    moneyUser1.setUserId(orderUserDemand.getUserId());
                    moneyUser1.setShopId(orderUserDemand.getUserId());
                    apiService.instalkMoneyUserCash(moneyUser1);
                }else{

                    moneyUser.setMoney(Arith.add(moneyUser.getMoney(), orderUserDemand.getPrice()));
                    apiService.updateMoneyUserCash(moneyUser);
                }
                return new WxplatformResult(WxplatformResultConstant.SUCCESS, "已收货");

            }
        }
        return new WxplatformResult(WxplatformResultConstant.FAILED, "不是您的商品");

    }
}
